<template>
  <div class="doctor pad">
    <div class="head">
      <span>医生管理</span>
    </div>
    <el-tabs type="border-card" class="m-t-b">
      <el-tab-pane label="医生管理">
        <el-button type="primary" @click="openAddDoctorDialog">
          <i class="el-icon-plus"></i>
          添加医生账号
        </el-button>
        <el-table :data="doctorList" stripe border class="m-t-b" v-loading="doctorLoading">
          <el-table-column label="手机号码" prop="psychologicalClinicianPhone"></el-table-column>
          <el-table-column label="医生姓名">
            <template slot-scope="scope">
              {{scope.row.clinicianName || '基本信息未完善'}}
            </template>
          </el-table-column>
          <el-table-column label="所属医院">
            <template slot-scope="scope">
              {{scope.row.hospitalName || '基本信息未完善'}}
            </template>
          </el-table-column>
          <el-table-column label="基本信息审核状态">
            <template slot-scope="scope">
              <el-tag type="warning" v-if="scope.row.clinicianStatus === '0'">医生未填写信息</el-tag>
              <el-tag v-else-if="scope.row.clinicianStatus === '1'">待管理员审核</el-tag>
              <el-tag type="success" v-else-if="scope.row.clinicianStatus === '2'">审核通过</el-tag>
              <el-tag type="danger" v-else-if="scope.row.clinicianStatus === '3'">审核失败</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="createDate"></el-table-column>
          <el-table-column label="登录状态">
            <template slot-scope="scope">
              <el-switch
                active-text="启用"
                inactive-text="禁用"
                v-model="scope.row.enable"
                @change="changeDoctorStatus($event, scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="180">
            <template slot-scope="scope">
              <el-button
                type="default"
                circle
                icon="el-icon-edit"
                title="修改手机号"
                @click="openEditDoctorDialog(scope.row)"
              ></el-button>
              <el-button
                type="danger"
                circle
                icon="el-icon-refresh"
                title="重置登录密码"
                @click="resetDoctorPassword(scope.row)"
              ></el-button>
              <el-button
                circle
                type="info"
                icon="el-icon-setting"
                @click="goDoctorInformation(scope.row)"
                title="管理医生基本信息"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="flex m-t-b"
          :page-size="pageSize"
          layout="prev, pager, next"
          @current-change="handleDoctorPagi"
          :total="doctorTotal"
        >
        </el-pagination>
      </el-tab-pane>
      <el-tab-pane label="医生标签管理">
        <el-button type="primary" @click="openAddLabelDialog">
          <i class="el-icon-plus"></i>
          添加医生标签
        </el-button>
        <el-table :data="labelList" stripe border class="m-t-b">
          <el-table-column label="医生标签" prop="doctorLabelName">
            <template slot-scope="scope">
              <el-tag type="success">{{scope.row.doctorLabelName}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="createDate"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button circle type="default" icon="el-icon-edit" @click="openEditLabelDialog(scope.row)"></el-button>
              <el-button circle type="danger" icon="el-icon-delete" @click="deleteLabel(scope.row)"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="flex m-t-b"
          :page-size="pageSize"
          layout="prev, pager, next"
          @current-change="handleLabelPagi"
          :total="labelTotal"
        >
        </el-pagination>
      </el-tab-pane>
    </el-tabs>
    <el-dialog :title="labelDialogTitle" :visible.sync="showLabelDialog">
      <el-form :model="label" label-position="top" ref="label" :rules="rules">
        <el-form-item label="医生标签名称" prop="doctorLabelName">
          <el-input v-model="label.doctorLabelName" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="hideLabelDialog">取 消</el-button>
        <el-button type="primary" @click="fetchAddLabel('label')" :loading="isDoing">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="doctorDialogTitle" :visible.sync="showDoctorDialog">
      <el-form :model="doctor" ref="doctor" :rules="rules" label-position="top">
        <el-form-item label="医生手机号" prop="psychologicalClinicianPhone">
          <el-input v-model="doctor.psychologicalClinicianPhone" type="number" />
        </el-form-item>
        <el-form-item
          label="医生登录密码"
          prop="psychologicalClinicianPassword"
          v-if="doctorDialogTitle !== '修改医生账号'"
        >
          <el-input v-model="doctor.psychologicalClinicianPassword" type="password" show-password />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="hideDoctorDialog">取 消</el-button>
        <el-button type="primary" @click="fetchAddDoctor('doctor')" :loading="isDoctorDoing">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  addDoctorLabel,
  updateDoctorLabel,
  deleteDoctorLabel,
  getDoctorLabelByPage,
  addDoctor,
  updateDoctor,
  setDoctorStatus,
  getDoctorByPage,
  resetDoctorPassword
} from '../api/hospitalAPI'
import { formatDate } from '../util'
export default {
  name: 'Doctor',
  data () {
    const validatePhone = (rules, value, callback) => {
      const phoneReg = /^1[3456789]\d{9}$/;
      if (!value) {
        return callback(new Error('请填写11位手机号'))
      };
      if (!phoneReg.test(value)) {
        return callback(new Error('手机号格式错误'))
      };
      callback()
    };
    const validatePassword = (rules, value, callback) => {
      if (!value) {
        return callback(new Error('请设置登录密码'))
      };
      if (value.length < 6 || value.length > 16) {
        return callback(new Error('密码长度为 6 ~ 16 个字符'))
      };
      if (!isNaN(value)) {
        return callback(new Error('密码不能为纯数字'))
      };
      callback()
    };
    return {
      isDoing: false,
      isDoctorDoing: false,
      labelDialogTitle: '添加医生标签',
      showLabelDialog: false,
      doctorDialogTitle: '添加医生账号',
      showDoctorDialog: false,
      doctorLoading: false,
      labelName: '',
      labelList: [],
      label: {
        doctorLabelName: ''
      },
      doctor: {
        psychologicalClinicianPhone: '',
        psychologicalClinicianPassword: '',
        psychologicalClinicianCode: ''
      },
      doctorList: [],
      loading: false,
      labelIsDoing: false,
      pageSize: 10,
      labelTotal: 0,
      doctorTotal: 0,
      labelId: '',
      doctorId: '',
      rules: {
        doctorLabelName: [
          { required: true, message: '医生标签名称不能为空', trigger: 'blur' }
        ],
        psychologicalClinicianPhone: [
          { required: true, validator: validatePhone, trigger: 'blur' }
        ],
        psychologicalClinicianPassword: [
          { required: true, validator: validatePassword, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    openAddLabelDialog () { // 打开医生标签添加弹出框
      this.label.doctorLabelName = '';
      this.labelDialogTitle = '添加医生标签';
      this.showLabelDialog = true
    },
    fetchLabels (index) { // 分页获取医生标签
      this.loading = true;
      getDoctorLabelByPage({
        count: this.pageSize,
        index
      })
      .then(res => {
        if (res.data.code === 1) {
          let list = res.data.data.list || [];
          this.labelTotal = res.data.data.totalRecord;
          this.labelList = list.map(item => {
            item.createDate = formatDate(item.createDate, 'ZH');
            return item
          });
        } else {
          this.$message.error(res.data.msg || '服务异常!')
        };
        this.loading = false
      })
      .catch(e => {
        this.loading = false;
        this.$message.error('服务异常!')
      })
    },
    openEditLabelDialog (data) { // 打开修改医生标签弹出框
      this.label.doctorLabelName = data.doctorLabelName;
      this.labelId = data.doctorLabelId;
      this.labelDialogTitle = '修改医生标签';
      this.showLabelDialog = true
    },
    deleteLabel (data) { // 删除医生标签
      this.$confirm(`确定将医生标签: ${data.doctorLabelName} 删除吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(res => {
        deleteDoctorLabel(data.doctorLabelId)
        .then(res => {
          if (res.data.code === 1) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.fetchLabels(1)
          } else {
            this.$message.error(res.data.msg || '服务异常!')
          }
        })
        .catch(e => {
          this.$message.error('服务异常!')
        })
      })
      .catch(e => {
        this.$message.error('服务异常!')
      })
    },
    hideLabelDialog () { // 隐藏医生标签弹出框
      this.showLabelDialog = false
    },
    fetchAddLabel (name) { // 添加医生标签
      this.$refs[name].validate(valid => {
        if (valid) {
          if (this.labelDialogTitle === '添加医生标签') {
            addDoctorLabel(this.label.doctorLabelName)
            .then(res => {
              if (res.data.code === 1) {
                this.$message({
                  type: 'success',
                  message: '添加成功'
                });
                this.showLabelDialog = false;
                this.fetchLabels(1)
              } else {
                this.$message.error(res.data.msg || '服务异常!')
              }
            })
            .catch(e => {
              this.$message.error('服务异常!')
            })
          } else {
            updateDoctorLabel({
              doctorLabelId: this.labelId,
              doctorLabelName: this.label.doctorLabelName
            })
            .then(res => {
              if (res.data.code === 1) {
                this.$message({
                  type: 'success',
                  message: '修改成功'
                });
                this.showLabelDialog = false;
                this.fetchLabels(1)
              } else {
                this.$message.error(res.data.msg || '服务异常!')
              }
            })
            .catch(e => {
              this.$message.error('服务异常!')
            })
          }
        } else {
          return false
        }
      })
    },
    handleLabelPagi (page) { // 医生标签分页
      this.fetchLabels(page)
    },
    openAddDoctorDialog () { // 打开添加医生弹出框
      this.doctor.psychologicalClinicianPhone = '';
      this.doctor.psychologicalClinicianPassword = '';
      // this.doctor.psychologicalClinicianCode = '';
      this.doctorDialogTitle = '添加医生账号';
      this.showDoctorDialog = true
    },
    hideDoctorDialog () { // 隐藏医生弹出框
      this.showDoctorDialog = false
    },
    fetchAddDoctor (name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          this.isDoctorDoing = true;
          if (this.doctorDialogTitle === '添加医生账号') {
            addDoctor({
              psychologicalClinicianPhone: this.doctor.psychologicalClinicianPhone,
              psychologicalClinicianPassword: this.doctor.psychologicalClinicianPassword,
              psychologicalClinicianCode: null
            })
            .then(res => {
              if (res.data.code === 1) {
                this.$message({
                  type: 'success',
                  message: '添加成功'
                });
                this.showDoctorDialog = false;
                this.fetchDoctorList(1);
              } else {
                this.$message.error(res.data.msg || '服务异常!')
              };
              this.isDoctorDoing = false
            })
            .catch(e => {
              this.isDoctorDoing = false;
              this.$message.error('服务异常!')
            })
          } else {
            updateDoctor({
              psychologicalClinicianId: this.doctorId,
              psychologicalClinicianPhone: this.doctor.psychologicalClinicianPhone
            })
            .then(res => {
              if (res.data.code === 1) {
                this.$message({
                  type: 'success',
                  message: '修改成功!'
                });
                this.showDoctorDialog = false;
                this.fetchDoctorList(1)
              } else {
                this.$message.error(res.data.msg || '服务异常!')
              }
            })
            .catch(e => {
              this.$message.error('服务异常!')
            })
          }
        } else {
          return false
        }
      })
    },
    fetchDoctorList (index) { // 查询医生账户列表
      this.doctorLoading = true;
      getDoctorByPage({
        count: this.pageSize,
        index
      })
      .then(res => {
        if (res.data.code === 1) {
          let list = res.data.data.list || [];
          this.doctorTotal = res.data.data.totalRecord;
          this.doctorList = list.map(item => {
            item.enable = item.psychologicalClinicianEnable === '1' ? true : false;
            item.createDate = formatDate(item.createDate, 'ZH');
            return item
          })
        } else {
          this.$message.error(res.data.msg || '服务异常!')
        };
        this.doctorLoading = false
      })
      .catch(e => {
        this.doctorLoading = false;
        this.$message.error('服务异常!')
      })
    },
    changeDoctorStatus (e, data) { // 改变医生账户状态
      let closeText = '禁用后该账户无法登录小程序';
      let openText = '启用后该账户能正常登录小程序';
      this.$confirm(`确定将账户: ${data.psychologicalClinicianPhone} ${e ? '启用' : '禁用'}? ${e ? openText : closeText}`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(res => {
        setDoctorStatus(data.psychologicalClinicianId, e ? 1 : 0)
        .then(res => {
          if (res.data.code === 1) {
            this.$message({
              type: 'success',
              message: '修改成功'
            });
            this.fetchDoctorList(1)
          } else {
            this.$message.error(res.data.msg || '服务异常!')
          }
        })
        .catch(e => {
          this.$message.error('服务异常!')
        })
      })
      .catch(err => {
        data.enable = !e
      })
    },
    openEditDoctorDialog (data) { // 打开医生修改手机号弹出框
      this.doctorId = data.psychologicalClinicianId;
      this.doctor.psychologicalClinicianPhone = data.psychologicalClinicianPhone;
      this.doctorDialogTitle = '修改医生账号';
      this.showDoctorDialog = true
    },
    resetDoctorPassword (data) { // 重置医生登录密码
      this.$confirm(`确定将账户: ${data.psychologicalClinicianPhone} 的密码重置吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(res => {
        resetDoctorPassword(data.psychologicalClinicianId)
        .then(res => {
          if (res.data.code === 1) {
            this.$message({
              type: 'success',
              message: '修改成功'
            });
            this.fetchDoctorList(1)
          } else {
            this.$message.error(res.data.msg || '服务异常!')
          }
        })
        .catch(e => {
          this.$message.error('服务异常!')
        })
      })
      .catch(e => {
        this.$message({
          type: 'info',
          message: '取消操作'
        })
      })
    },
    handleDoctorPagi (page) { // 医生分页
      this.fetchDoctorList(page)
    },
    goDoctorInformation (data) { // 进入医生信息页面
      this.$router.push(`/mental/doctor/detail/${data.psychologicalClinicianId}/${data.clinicianStatus ? data.clinicianStatus : 0}`)
    }
  },
  created () {
    this.fetchLabels(1);
    this.fetchDoctorList(1);
  }
}
</script>
<style lang="scss">
  .doctor {

  }
</style>
